﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Axiom.Hermetica
{
	public static class BitmapExtensions
	{
		public static byte[] ToBytes(this ImageSource source)
		{
			return BufferFromImage(source as BitmapImage);
		}

		private static byte[] BufferFromImage(BitmapImage img)
		{
			byte[] result = null;

			if (img != null)
			{
				using (MemoryStream memStream = new MemoryStream())
				{
					JpegBitmapEncoder encoder = new JpegBitmapEncoder();
					encoder.Frames.Add(BitmapFrame.Create(img));
					encoder.Save(memStream);

					result = memStream.ToArray();
				}

			}

			return result;
		}

		public static byte[] ToBytes(this BitmapImage bitmap)
		{
			Stream stream = bitmap == null ? null : bitmap.StreamSource;
			if (!stream.CanRead)
			{
				return BufferFromImage(bitmap);
			}

			byte[] bytes = new byte[] { };

			if (stream == null || stream.Length == 0)
			{
				var names = Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(a => a.Contains("embeded.images")).ToList();
				Random rnd = new Random((int)DateTime.Now.Ticks);
				string imagename = names[rnd.Next(0, names.Count)];
				stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imagename);
			}

			using (BinaryReader br = new BinaryReader(stream))
			{
				bytes = br.ReadBytes((Int32)stream.Length);
			}

			return bytes;
		}

		public static BitmapImage ToBitmapImage(this byte[] bytes)
		{
			BitmapImage image = null;
			using (var stream = new MemoryStream(bytes))
			{
				image = new BitmapImage();
				image.BeginInit();
				image.StreamSource = stream;
				image.EndInit();
			}
			return image;
		}

		public static ImageSource ToImageSource(this System.Drawing.Image image)
		{
			BitmapImage bitmapImage = null;
			try
			{
				using (MemoryStream memory = new MemoryStream())
				{
					image.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
					memory.Position = 0;
					bitmapImage = new BitmapImage();
					bitmapImage.BeginInit();
					bitmapImage.StreamSource = memory;
					bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
					bitmapImage.EndInit();
				}
			}
			catch (Exception ex)
			{
				/// ... ignore, return null
			}
			return bitmapImage;
		}
	}	
}
